package com.paper.tiger.easy.rpc.s.client.registy.handler;

import com.alibaba.fastjson.JSON;
import com.paper.tiger.easy.rpc.core.RegisterData;
import com.paper.tiger.easy.rpc.core.ServerType;
import com.paper.tiger.easy.rpc.s.client.client.ContextManager;
import com.paper.tiger.easy.rpc.s.client.registy.common.RegisterConfig;
import com.paper.tiger.easy.rpc.s.client.registy.service.RespService;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * [简要描述]: 处理服务请求
 * [详细描述]:
 *
 * @author ZouHaiBo
 * @version 1.0, 2021/6/16 15:35
 * @since JDK 1.8
 */
public class ClientServiceHandler extends SimpleChannelInboundHandler<RegisterData>
{

    private static Logger logger = LoggerFactory.getLogger(ClientServiceHandler.class);

    static ThreadPoolExecutor executor = new ThreadPoolExecutor(1,2,60, TimeUnit.SECONDS,new ArrayBlockingQueue<>(1000)
            ,new ThreadPoolExecutor.AbortPolicy());
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, RegisterData msg) throws Exception
    {
        logger.info("ClientServiceHandler 接收到服务数据，数据为：{}", JSON.toJSONString(msg));
        Integer type = msg.getType();
        ServerType serverType = ServerType.getByCode(type);

        RespService respService = (RespService) RegisterConfig.get(serverType.getRegisterName());

        executor.execute(()-> respService.service(ctx,msg));


    }

    @Override
    public void channelActive(ChannelHandlerContext ctx)
    {
        ContextManager.getInstance().setRegistyChannel(ctx.channel());
        ctx.fireChannelActive();
    }
}
